<?php
class ImagesController extends AppController {

	var $name = 'Images';
	var $helpers = array('Html', 'Form');

	
	function beforeFilter() {
    	$this->Auth->allow('thumb');
    }
    	
	
	function thumb($id = null)
	{
			$this->Image->recursive = -1;
	    	$img = $this->Image->findById($id);    
			
	    	$this->Image->set($this->data);
	    	
			if(empty($img['Image']['id'])){
                die("No source image");
            }
            
           
            $width   = (!isset($_GET['w'])) ? 100 : $_GET['w'];
            $height  = (!isset($_GET['h'])) ? 150 : $_GET['h'];    
            $quality = (!isset($_GET['q'])) ? 100  : $_GET['q'];
            $filters = (!isset($_GET['fltr']) ? '' : $_GET['fltr']);
            $f = (!isset($_GET['f']) ? 'png' : $_GET['f']);
            
            $sourceFilename = WWW_ROOT . 'img/' . $img['Image']['filename'];
            
          

            if(is_readable($sourceFilename)){
                App::import('Vendor', 'phpthumb', array('file' => 'phpthumb' . DS . 'phpthumb.class.php'));
                
                $phpThumb = new phpThumb();

                $phpThumb->setSourceFilename($sourceFilename); 
                $phpThumb->setParameter('w', $width);
                $phpThumb->setParameter('f', $f);
                $phpThumb->setParameter('h', $height);
                $phpThumb->setParameter('q', $quality);
                $phpThumb->setParameter('fltr', $filters);
                $phpThumb->setParameter('max_source_pixels',4000000);
                $phpThumb->setParameter('config_document_root', '');
                $phpThumb->setParameter('config_temp_directory', APP . 'tmp');
                $phpThumb->setParameter('config_cache_directory', CACHE);
                $cacheFilename = md5($_SERVER['REQUEST_URI']);
                $cache_file = $phpThumb->config_cache_directory.$cacheFilename;
                $phpThumb->setParameter('cache_filename', $cache_file);
                
                
                if(!is_file($phpThumb->cache_filename)){ // Check if image is already cached.
                    if ($phpThumb->GenerateThumbnail())
                    {
						
                    	$phpThumb->RenderToFile($cache_file);
                       
                    } else {
                        die('Failed: '.$phpThumb->error);
                    }
                }
            
             if(is_file($cache_file)){ // If thumb was already generated we want to use cached version
                $cachedImage = getimagesize($cache_file);
                header('Content-Type: '.$cachedImage['mime']);
                readfile($phpThumb->cache_filename);
                exit;
            }
            else
            {
            	echo 'not file';
            }
            
            
            } else { // Can't read source
                die("Couldn't read source image");
            }
		
	}

	function add() {
		$user = $this->Auth->user();
			
		if (!empty($this->data)) {
			unset($this->data['Image']['id']);
			
			$profile = $this->Image->Profile->findByUserId($user['User']['id']);
			
			if(!isset($this->data['Image']['story_id']))
			 $this->data['Image']['profile_id'] = $profile['Profile']['id'];
			
			$random_file_name = substr(md5(microtime() . $this->data['Image']['File']['tmp_name']),0,10);
			
			
			$badFile = false;
			switch($this->data['Image']['File']['type'])
			{
				case 'image/pjpeg':
					$extension = '.jpg';
					break;
				case 'image/gif':
					$extension = '.gif';
					break;
				case 'image/jpg':
					$extension = '.jpg';
					break;
				case 'image/png':
					$extension = '.png';
					break;
				case 'image/jpeg':
					$extension = '.jpg';
					break;
				case 'image/bmp':
					$extension = '.bmp';
					break;
					
				default:
					$badFile = true;
			}
			
			//debug($this->data);
			//exit();
			$this->Image->set($this->data);
			if(!$badFile)
			{
				$relative_path =  'user/' . $random_file_name . $extension;
				$new_path = WWW_ROOT . 'img' . DS . 'user' . DS . $random_file_name . $extension;
				$file_size = getimagesize($this->data['Image']['File']['tmp_name']);
				$fileTooLarge = false;
				if($file_size[0] * $file_size[1] > 4800000)
				{
					$fileTooLarge = true;
						$this->Session->setFlash(__('Image too large.', true));
					$this->set('fileTooLarge',true);
				}
				
				if(!$fileTooLarge)
				{
					move_uploaded_file($this->data['Image']['File']['tmp_name'], $new_path); 
					unset($this->data['Image']['File']);
					$this->data['Image']['local_path']= $new_path;
					$this->data['Image']['filename']  = $relative_path;
					$this->Image->create();
					if ($this->Image->save($this->data)) {					
						if(isset($this->data['Image']['profile_id']))
						{
							
							/* delete the old images */
							/* profiles can have only one image */
						
							$this->Image->recursive = -1;
							$old_images = $this->Image->find('all', array('conditions' => array('profile_id' => $this->data['Image']['profile_id'], 'NOT' => array('Image.id' => $this->Image->id))));
							
							foreach($old_images as $old_image)
							{
							 $this->Image->delete($old_image['Image']['id']);
							 @unlink($old_image['Image']['local_path']);
							}
							
							$this->Session->setFlash(__('The image has been saved.', true));
							$this->redirect(array('controller' => 'profiles', 'action'=>'view', $profile['Profile']['id']));
						}
						else if($this->data['Image']['story_id'])
						{
							$this->Session->setFlash(__('The image has been saved.', true));
							$this->redirect(array('controller' => 'stories', 'action'=>'view', $this->data['Image']['story_id']));
							
						}
					} else {
						$this->Session->setFlash(__('Image error. Try again.', true));
					}
			  }		
			  else
			  {
			  	if(isset($this->data['Image']['story_id']))
			  	{
			  	$story = $this->Image->Story->findById($this->data['Image']['story_id']);
				
				if(!isset($story['Story']['id']))
				{
					$this->Session->setFlash(__('Unable to add image.', true));
					$this->redirect('/profiles/view/');
				}
				else
				{
				
					if($story['Story']['user_id'] != $user['User']['id'])
					{
						$this->Session->setFlash(__('Unable to add image.'), true);
						$this->redirect('/stories/view/' . $story['Story']['id']);
					}
					else
					{
						$this->data['Image']['story_id'] = $story['Story']['id'];						
						$this->Image->set($this->data);
						$this->set('story', $story);
					}
				}
			  	}
			  }			
			}
			
		}
		else
		{
			if(isset($_GET['story_id']) || isset($this->data['Image']['story_id']))
			{
				if(isset($this->data['Image']['story_id']))
				 $_GET['story_id'] = $this->data['Image']['story_id'];
				 
				$this->Image->Story->recursive = -1;
				$story = $this->Image->Story->findById($_GET['story_id']);
				
				if(!isset($story['Story']['id']))
				{
					$this->Session->setFlash(__('Unable to add image.', true));
					$this->redirect('/profiles/view/');
				}
				else
				{
				
					if($story['Story']['user_id'] != $user['User']['id'])
					{
						$this->Session->setFlash(__('Unable to add image.'), true);
						$this->redirect('/stories/view/' . $story['Story']['id']);
					}
					else
					{
						$this->data['Image']['story_id'] = $story['Story']['id'];						
						$this->Image->set($this->data);
						$this->set('story', $story);
					}
				}
			}
		}
		//$stories = $this->Image->Story->find('list');
		//$profiles = $this->Image->Profile->find('list');
		//$this->set(compact('stories', 'profiles'));
	}


	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for image.', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Image->del($id)) {
			$this->Session->setFlash(__('Image deleted.', true));
			$this->redirect(array('action'=>'index'));
		}
	}

}
?>